﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
using Microsoft.Win32;

namespace eeenno.ReaderEngine.Utilities
{
    public class ConfigurationManager
    {
        private static string _INI_FILE_PATH = System.IO.Path.GetDirectoryName
            (System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) +
            "\\SpeeedReader.ini";     

        private Dictionary<string, string> _settings = new Dictionary<string, string>();

        /// <summary>
        /// Dumps the settings file to a string
        /// </summary>
        /// <returns>settings file dump</returns>
        public string DumpSettings()
        {
            string ret_val = Environment.NewLine + "---Settings Dump---";            
            for (int i = 0; i < _settings.Count; i++)
            {
                if (!(_settings.ElementAt(i).Key.ToLower().Contains("password") || _settings.ElementAt(i).Key.ToLower().Contains("username")))
                {
                    ret_val += Environment.NewLine + _settings.ElementAt(i).Key + " -- " + _settings.ElementAt(i).Value;
                }
            }
            return ret_val + "---" + Environment.NewLine;
        }

        /// <summary>
        /// Gets value of the setting with the specified name
        /// </summary>
        /// <param name="option">Name of settings</param>
        /// <returns>value of specified setting</returns>
        public string GetSetting(string option)
        {
            try
            {
                string temp = _settings[option];
                if (temp == "\"\"")
                    return String.Empty;
                else
                    return temp;
            }
            catch (Exception e)
            {
                return String.Empty;
            }
        }

        public void SetSetting(string option, string value)
        {
            try
            {
                _settings[option] = value;
            }
            catch (Exception e)
            {

            }
        }

        public long GetLongSetting(string option)
        {
            try
            {
                return long.Parse(GetSetting(option));
            }
            catch (FormatException e)
            {
                return 10;
            }
        }

        public void SetLongSetting(string option, long value)
        {
            SetSetting(option, value.ToString());
        }

        public int GetIntSetting(string option)
        {
            try
            {
                return int.Parse(GetSetting(option));
            }
            catch (FormatException e)
            {
                return 10;
            }
        }

        public void SetIntSetting(string option, int value)
        {
            SetSetting(option, value.ToString());
        }

        public bool GetBoolSetting(string option)
        {
            try
            {
                return bool.Parse(GetSetting(option));
            }
            catch (FormatException e)
            {
                return false;
            }
        }

        public void SetBoolSetting(string option, bool value)
        {
            SetSetting(option, value.ToString());
        }

        public bool WriteINIFile()
        {
            try
            {
                using(StreamWriter sw = new StreamWriter(_INI_FILE_PATH))
                {
                
                    for(int i = 0; i < _settings.Count; i++)
                    {
                        string parameter = _settings.ElementAt(i).Key + ";";
                        if (_settings.ElementAt(i).Value == String.Empty)
                            parameter += "\"\"";
                        else
                            parameter += _settings.ElementAt(i).Value;
                        sw.WriteLine(parameter);
                    }
                }                
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public bool ReadINIFile()
        {
            try
            {
                using (StreamReader sr = new StreamReader(_INI_FILE_PATH))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //Allow for comments and empty lines
                        if (line == String.Empty || line.StartsWith("#"))
                            continue;

                        string[] kvPair = line.Split(';');

                        // Format must be option = value.
                        if (kvPair.Length != 2)
                            continue;

                        // If the option already exists, it's overwritten.
                        _settings[kvPair[0].Trim()] = kvPair[1].Trim();
                    }
                }
            }
            catch (IOException e)
            {
                return false;
            }
            return true;
        }

        public string ReadClassesRootKey(string KeyName, string sub_key)
        {
            // Opening the registry key
            RegistryKey registry_key = Registry.ClassesRoot;
            // Open a subKey as read-only
            RegistryKey subkey = registry_key.OpenSubKey(sub_key);
            // If the RegistrySubKey doesn't exist -> (null)
            if (subkey == null)
            {
                return null;
            }
            else
            {
                try
                {
                    return (string)subkey.GetValue(KeyName.ToUpper());
                }
                catch (Exception e)
                {
                    LogManager.LogError("ConfigurationManager.ReadKey", "There was an error reading " + KeyName + "--" + e.Message);
                    return null;
                }
                finally
                {
                    if (registry_key != null)
                    {
                        registry_key.Close();
                    }
                    if (subkey != null)
                    {
                        subkey.Close();
                    }
                }
            }
        }      
    }
}
